from pymongo import MongoClient
import pymongo
import os
import numpy as np
import sys
import audiofile
import opensmile
smile = opensmile.Smile(
         feature_set=opensmile.FeatureSet.ComParE_2016,
         feature_level=opensmile.FeatureLevel.Functionals,
     )
client = MongoClient(port=27017)
db=client['tiktok_p2_1']
i=0
#['thriftshop', 'upcycling', 'beautyhacks', 'wrestlemania', 'mystyle', 'superbowllv', 'defrosting', 'ratatouillemusical', 'productivity', 'loveyourinsecurities', 'falldiy', 'glasspainting', 'whereilive', 'foodie', 'nonuancenovember', 'roomtour', 'inverted', 'stemlife', 'fallfashion', 'festivefashion', 'science101', 'lovestory', 'vinylclub', 'homeproject', 'myroutine', 'nbaisback', 'cleantok', 'wishlist', 'imbusyrightnow', 'bakingszn', 'timewarpjump', 'healthyliving', 'plantparent', 'couplethings', 'watchmegrow', 'artmas', 'youwantmore', 'myrecommendation', 'nflplayoffs', 'tiktokdiy', 'blackandproud', 'sidetable', 'passover', 'fitnesslife', 'easydiy', 'stpatricksday', 'myhobby', 'beautyhack', 'holidayvibes', 'unwrapthedeals', 'timewarpwaterfall', 'meditation101', 'feliznavidad', 'onlinedating', 'dinnerparty', 'makeitvogue', 'smallbusiness', 'relationshipstorytime', 'familyimpression', 'dailyvlog', 'worldseries', 'cozyathome', 'animation', 'homebusiness', 'thankstoher', 'ramadanmubarak', 'tiktokfitness', 'coldweather', 'earthday', 'haventseen', 'wip', 'lifestyle', 'learnwithme', 'laughingduet', 'mobilegame', 'coversforlovers', 'gamenight', 'thrifting', 'olympicscountdown', 'imaghost', 'nativefamily', 'zodiacsign', 'passingthephone', 'easyrecipe', 'horrortok', 'hereforrmhc', 'bakedoats', 'puppybowl', 'kissyourpet', 'promszn', 'interiordesign', 'sfxmakeup', 'nbaallstar', 'blackcreatives', 'workingathome', 'skatelife', 'gaminglife', 'graphicdesign', 'tortillatrend', 'christmas2020', 'howbizarre', 'carhacks', 'snowstorm', 'housetour', 'mlkday', 'healthyheart', 'pleasedontgo', 'showupshowoff', 'happyhanukkah', 'perfectdrink', 'neontwin', '90saesthetic', 'holidaycountdown', 'tiktokfashionmonth', 'givingszn', 'royalrumble', 'recordsday', 'ootd', 'meleaving', 'homemade', 'happyhalloween', 'holidaydecor', 'welldone', 'rareaesthetic', 'carsoftiktok', 'foodtiktok', 'heinzhalloween', 'selfimprovement', 'songfacts', 'perfectgifts', 'joblife', 'autismawareness', 'melaninmagic', 'ecohacks', 'mifamilia', 'veteransday', 'thinkingabout', 'learnontiktok', 'seitan', 'growupwithme', 'ohno', 'tabletop', 'colorblast', 'yellow', 'diwali', 'emophase', 'problemsolved', 'neonshadow', 'cartiktok', 'homeimprovement', 'diyprojects', 'careeradvice', 'naturescereal', 'fitnessroutine', 'cleaningtiktok', 'hellowinter', 'bekind', 'gamingtiktok', 'winterbeautytips', 'familyrecipe', 'moneytok', 'tiktokwildlifeday', 'perfectmatch', 'myhaul', 'nbadraft', 'gamingsetup', 'visionboard', 'takeabite', 'wordsofwisdom', 'halloweenlook', '2018vs2021', 'fanedit', 'givethanksnotpranks', 'hyperfixated', 'inlove', 'yougotthis', 'inspirationalquotes', 'homecook', 'feelinggood', 'arabtiktok', 'happyholidays', 'vaccinatedfor', 'wildanimals', 'sheearnedit', 'rnbvibes', 'holidaytiktok', 'homecooked', 'womeninstem', 'dramaticmoments', 'nowlookatthis', 'givingthanks', 'lgbtqhistory', 'healthycooking', 'aprilfools', 'whenwomenwin', 'personalfinance', 'comingofage', 'roundofapplause', 'homeoffice', 'ourtype', 'comfortfood', 'notaperfectperson', 'homecafe', 'holidaycrafts', 'projectcar', 'clingypet', 'seashanty', 'baseballisback', 'holidaytreats', 'planttiktok', 'happyholi', 'foodontiktok', 'catchphrases', 'fetapasta', 'tiktokcars', 'transvisibilityday', '2021affirmations', 'goodmorning', 'greenscreenscan', 'stopasianhate', 'lunarnewyear', 'tiktokfood', 'welcome2021', 'valentinesdiy', 'springvibes', 'hellospring', 'onhold', 'lookbook', 'needtoknow', 'motivationmonday', 'typing', 'homediy', 'stepbystep', 'winterfit', 'happyeaster', 'yearontiktok', 'whatilearned', 'whenwewereyounger', 'weekendvibes', 'somethingyoulearned', 'groupchat', 'itwasntaphase', 'amongus', 'springoutfit', 'ontherunway', 'gamergoals', 'tiktoktailgate', 'athletesoftiktok', 'spookytreats', 'bye2020', 'mycostume', 'dayandnight', 'siblinggoals', 'nhlfaceoff', 'competitivegaming', 'galentinesday', 'albumcover', 'fallguysmoments', 'petsontiktok', 'holidaysourway', 'herstory', 'doctorsoftiktok', 'sabiasque', 'mypfp', 'crowdcheers', 'oscars', 'holidaymusic', 'makeblackhistory', 'fantheory', 'wintersports', 'tiktoktutorial', 'inkdrawing', 'diceroll', 'sehablaespañol', 'raisedby', 'nowruz', 'valentinesday', 'theatrekids', 'cocinando', 'readysetshop', 'skincare101', 'micellarrewind', 'sheesh', 'tipsandtricks', 'puppiesonly', 'halloweenishere', 'stylehacks', 'baseballtiktok', 'marchmadness', 'isthisavailable', 'colddays', 'weirdpets', 'gettheretogether', 'guitartok', 'winterfashion', 'thriftflip']
collist=['gaminglife', 'whatilearned', 'happyholi', 'stpatricksday', 'ontherunway', 'joblife', 'homecooked', 'tiktokcars', 'gettheretogether', 'zodiacsign', 'hellowinter', 'healthyheart', 'tiktokfood', 'petsontiktok', 'homecook', 'timewarpwaterfall', 'tiktokdiy', 'graphicdesign', 'holidaycrafts', 'foodtiktok', 'emophase', 'neontwin', 'tiktokwildlifeday', 'nflplayoffs', 'smallbusiness', 'needtoknow', 'superbowllv', 'mifamilia', 'nbaallstar', 'hyperfixated', 'couplethings', 'kissyourpet', 'greenscreenscan', 'tabletop', 'wildanimals', 'stemlife', 'easyrecipe', 'fallguysmoments', 'inkdrawing', 'gamenight', 'planttiktok', 'yellow', 'imaghost', 'mlkday', 'perfectmatch', 'homecafe', 'siblinggoals', 'whenwomenwin', 'promszn', 'halloweenlook', 'christmas2020', 'diyprojects', '2018vs2021', 'tiktokfashionmonth', 'theatrekids', 'mystyle', 'artmas', 'wrestlemania', 'cleaningtiktok', 'mypfp', 'holidaymusic', 'beautyhack', 'carsoftiktok', 'moneytok', 'homediy', 'holidaysourway', 'ratatouillemusical', 'happyhanukkah', 'colddays', 'thriftflip', 'carhacks', 'familyimpression', 'aprilfools', 'falldiy', 'recordsday', 'givingthanks', 'cartiktok', 'fallfashion', 'homeimprovement', 'crowdcheers', '2021affirmations', 'mobilegame', 'problemsolved', 'herstory', 'weirdpets', 'nbaisback', 'haventseen', 'baseballtiktok', 'ohno', 'clingypet', 'fantheory', 'coversforlovers', 'homemade', 'learnwithme', 'happyeaster', 'womeninstem', 'seashanty', 'somethingyoulearned', 'whenwewereyounger', 'vinylclub', 'productivity', 'animation', 'yearontiktok', 'coldweather', 'rareaesthetic', 'sidetable', 'onlinedating', 'puppybowl', 'perfectdrink', 'colorblast', 'sheesh', 'roomtour', 'thriftshop', 'sfxmakeup', 'housetour', 'perfectgifts', 'myrecommendation', 'nowruz', 'weekendvibes', 'givingszn', 'royalrumble', 'neonshadow', 'springvibes', 'learnontiktok', 'defrosting', 'doctorsoftiktok', 'healthycooking', 'dailyvlog', 'stylehacks', 'nhlfaceoff', 'ecohacks', 'catchphrases', 'wishlist', 'personalfinance', 'meditation101', 'diceroll', 'youwantmore', 'wordsofwisdom', 'upcycling', 'stepbystep', 'wip', 'baseballisback', 'welldone', 'onhold', 'unwrapthedeals', 'halloweenishere', 'notaperfectperson', 'typing', 'foodie', 'beautyhacks', 'inspirationalquotes', 'snowstorm', 'tipsandtricks', 'puppiesonly', 'fanedit', 'howbizarre', 'marchmadness', 'myhaul', 'meleaving', 'blackandproud', 'dayandnight', 'veteransday', 'fitnesslife', 'readysetshop', 'earthday', 'valentinesdiy', 'nonuancenovember', 'pleasedontgo', 'amongus', 'imbusyrightnow', 'naturescereal', 'holidaytiktok', 'itwasntaphase', 'winterfashion', 'melaninmagic', 'whereilive', 'laughingduet', 'winterfit', 'groupchat', 'myhobby', '90saesthetic', 'nowlookatthis', 'inlove', 'projectcar', 'relationshipstorytime', 'happyhalloween', 'yougotthis', 'galentinesday', 'welcome2021', 'motivationmonday', 'festivefashion', 'visionboard', 'comfortfood', 'givethanksnotpranks', 'fetapasta', 'horrortok', 'bekind', 'inverted', 'careeradvice', 'growupwithme', 'hellospring', 'feelinggood', 'sabiasque', 'isthisavailable', 'workingathome', 'goodmorning', 'bye2020', 'athletesoftiktok', 'takeabite', 'easydiy', 'watchmegrow', 'holidaydecor', 'seitan', 'myroutine', 'foodontiktok', 'holidaytreats', 'dinnerparty', 'gamergoals', 'tiktokfitness', 'vaccinatedfor', 'wintersports', 'sheearnedit', 'transvisibilityday', 'familyrecipe', 'cozyathome', 'gamingtiktok', 'raisedby', 'thankstoher', 'thinkingabout', 'healthyliving', 'plantparent', 'hereforrmhc', 'oscars', 'valentinesday', 'makeitvogue', 'lifestyle', 'happyholidays', 'lunarnewyear', 'olympicscountdown', 'bakingszn', 'competitivegaming', 'timewarpjump', 'homeproject', 'ourtype', 'cleantok', 'fitnessroutine', 'glasspainting', 'holidayvibes', 'blackcreatives', 'makeblackhistory', 'nativefamily', 'nbadraft', 'lovestory', 'dramaticmoments', 'tortillatrend', 'bakedoats', 'winterbeautytips', 'interiordesign', 'lookbook', 'holidaycountdown', 'ootd', 'selfimprovement', 'albumcover', 'passover', 'homebusiness', 'guitartok', 'tiktoktailgate', 'mycostume', 'science101', 'gamingsetup', 'homeoffice', 'springoutfit', 'rnbvibes', 'autismawareness', 'roundofapplause', 'passingthephone', 'tiktoktutorial', 'thrifting', 'songfacts', 'loveyourinsecurities', 'skincare101']

for col in collist[:1]:
    for item in db[col].find():
        if os.path.exists('E:\\wav_pi\\' + item['_id'] + '.wav'):
            signal, sampling_rate = audiofile.read('E:\\wav_pi\\' + item['_id'] + '.wav')
        else:
            os.system('ffmpeg -i E:\\Tiktok\\Hashtag\\' + col + '\\' + item['_id'] + '.mp4 E:\\wav_pi\\' + item[
                '_id'] + '.wav')
            signal, sampling_rate = audiofile.read('E:\\wav_pi\\' + item['_id'] + '.wav')

        for fn in range(10):
            if len(item['frame_level']['f'+str(fn)]['audio'])>0:
                continue
            k=smile.process_signal(signal[:,(len(signal[1])//10)*fn:(len(signal[1])//10)*(fn+1)],sampling_rate=sampling_rate)
            k=k.values.tolist()[0]
            #db[col].update_one({'_id': item['_id']}, {'$set':{'video_feature.audio.yamnet':k}})
            db[col].update_one({'_id':  item['_id']}, {'$set': {'frame_level.f' + str(fn)+'.audio': k}})
            print('update success ',col,item['_id'])
            i += 1


